<?php
namespace common\util;

class ArrayUtil{
    
    
    /**
     * 
     * @param array $array
     * @param array $defaultArray
     */
    public static function  fill(&$defaultArray,$array){
        $keys = array_keys($defaultArray);
        foreach ($keys as $key){
            if(array_key_exists($key, $array)){
                $defaultArray[$key] = $array[$key];
            }
        }
        return $defaultArray;
    }  
    
    /**
     * 过滤数组字段
     * @param array $array
     * @param array $keys
     * @return multitype:unknown
     */
    public static function filter($array,$keys){
        $result = [];
        foreach ($keys as $key){
            if(array_key_exists($key, $array)){
                $result[$key] = $array[$key];
            }
        }
        return $result;
    }
    
    public static function getSubArrayFromIndexs($array,$indexs){
        $result = [];
        foreach ($indexs as $index){
            $result [] = $array[$index];
        }
        return $result;
    }
    
    /**
     * 获取列表中某个字段列表(字段值不为空,且唯一)
     * @param array $list
     * @param string $column
     */
    public static function getKeyValuesFromArray($list,$column){
        if(empty($list)){
            return [];
        }
        $ids = array_map(function($item) use($column){
            return $item[$column];
        }, $list);
        return array_unique(array_filter($ids));
    } 
    
    public static function group($array,$key){
        $result = [];
        foreach ($array as $item){
            $result[$item[$key]][] = $item;
        }
        return $result;
    }
    
    /**
     * 数组转成map
     * @param array $array
     * @param string $key
     * @return multitype:unknown
     */
    public static function  array2Map($array,$key){
        $result = [];
        foreach ($array as $item){
            $result[$item[$key]] = $item;
        }
        return $result;
    }
    
    public static function getValueFromMap($map,$key,$default=''){
        if(array_key_exists($key, $map)){
            return $map[$key];
        }
        return $default;
    }
    
    /**
     * 根据父级数组顺序排序子序列
     * @param array $array
     * @param array $subArray
     */
    public static function sortSubArrayByArrayOrder($array,$subArray){
        $result = [];
        foreach ($array as $val){
            if(in_array($val, $subArray)){
                $result[] = $val;
            }
        }
        var_dump($array);
        var_dump($subArray);
        var_dump($result);exit;
        return $result;
    }
}